<?php

namespace app\api\service;

use app\api\validate\UserCollectionValidate;
use support\spark\model\user\UserCollection;

class UserCollectService
{
    /**
     * 获取我的收藏
     * @param $param
     * @return array
     */
    public function getMyCollect($param)
    {
        $userCollectModel = new UserCollection();
        $list= $userCollectModel->getPaginateList([
            'user_id' => \Tinywan\Jwt\JwtToken::getUser()['id']
        ],['*'],[],[],$param['limit']);
        return dataReturn(0,'ok',$list);
    }

    /**
     * 添加/取消收藏
     * @param $param
     * @return array
     */
    public function addCollect($param)
    {

        $validate = new UserCollectionValidate();
        if (!$validate->check($param)) {
            return dataReturn(-1, $validate->getError());
        }
        $userInfo = \Tinywan\Jwt\JwtToken::getUser();;
        $userCollectModel = new UserCollection();
        $has = $userCollectModel->findOne([
            'goods_id' => $param['goods_id'],
            'user_id' => $userInfo['id']
        ])['data'];
        if (!empty($has)) {
            return dataReturn(0, '收藏成功');
        }

        $param['user_id'] = $userInfo['id'];
        $param['create_time'] = now();
        $res = $userCollectModel->insertOne($param);
        if ($res['code'] != 0) {
            return $res;
        }

        return dataReturn(0, '收藏成功');
    }

    /**
     * 移除收藏
     * @param $id
     * @return array
     */
    public function removeCollect($id)
    {
        $userCollectModel = new UserCollection();
        return $userCollectModel->delByWhere([
            'user_id' => getUserInfo()['id'],
            'id' => $id
        ]);
    }

    /**
     * 移除收藏
     * @param $goodsId
     * @return array
     */
    public function removeCollectByGoodsId($goodsId)
    {
        $userCollectModel = new UserCollection();
        return $userCollectModel->delByWhere([
            'user_id' => getUserInfo()['id'],
            'goods_id' => $goodsId
        ]);
    }
}
